<!--
 * @Descripttion:
 * @version: 1.0.0
 * @Author: htang
 * @Date: 2024-01-22 17:33:38
 * @LastEditors: htang
 * @LastEditTime: 2024-02-02 09:38:23
-->
<template>
  <div class="jeecg-basic-table station-device-view">
    <div class="tip flex items-center">
      <a-page-header :title="'站点设备(' + stationInfo.name + ')'" @back="$router.go(-1)" />
    </div>
    <div class="device-main flex justify-between">
      <div class="device" :class="[deviceList.length == 0 ? 'flex flex-wrap justify-center items-center' : 'device-grid']">
        <template v-if="deviceList.length !== 0">
          <template v-for="(vo, idx) in deviceList" :key="idx">
            <a-card :title="vo.name" class="device-item">
              <div class="item-name flex justify-between mb-4">
                <span>开关:</span>
                <a-radio-group v-model:value="vo.state.running" @change="saveDeviceMessage(vo)" :disabled="vo.state.auto == 1 ? true : false">
                  <a-radio :style="radioStyle" :value="0">关闭</a-radio>
                  <a-radio :style="radioStyle" :value="1">开启</a-radio>
                </a-radio-group>
              </div>
              <div class="item-name flex justify-between mb-4">
                <span>手自状态:</span>
                <a-radio-group v-model:value="vo.state.auto" @change="saveDeviceAuto(vo)">
                  <a-radio :style="radioStyle" :value="0">手动</a-radio>
                  <a-radio :style="radioStyle" :value="1">自动</a-radio>
                </a-radio-group>
              </div>
            </a-card>
          </template>
        </template>
        <template v-else>
          <a-empty :image="simpleImage" />
        </template>
      </div>
      <div id="meta-main" class="meta-main">
        <div id="device-meta">
          <Editor />
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, getCurrentInstance, onMounted } from 'vue';
import Editor from '@/components/Meta2D/Editor/index.vue';
import { useSelection } from '@/services/selections';
import { stationInfoApi } from '@/api/station';
import { equipmentListApi } from '/@/api/equipment';
import { Empty, message } from 'ant-design-vue';
import { getToken } from '/@/utils/auth';
import { useGlobSetting } from '/@/hooks/setting';
import { useCommonStoreWithOut } from '@/store/modules/common';
import Template1 from '../../demo/jeecg/JVxeTableDemo/layout-demo/Template1.vue';

const { selections } = useSelection();

const glob = useGlobSetting();

let { proxy } = getCurrentInstance();

let simpleImage = reactive(Empty?.PRESENTED_IMAGE_SIMPLE);

// 设备列表
let deviceList = ref([]);

// 站点信息
let stationInfo = ref({});

let radioStyle = reactive({
  display: 'flex',
  height: '30px',
  lineHeight: '30px',
});

let socketMessage = ref({});

// 初始化 WebSocket
function initWebSocket() {
  deviceList.value = [];
  meta2d.socketFn = (msg, context) => {
    let info = JSON.parse(msg);
    socketMessage.value = info;
    if (info.messageType == 3 && info['data'] !== '失败') {
      message.success('下发成功');
    }
    if (info.data['data']) {
      let dataList = JSON.parse(info.data['data']);
      if (info.data['ykInfo']) {
        let ykInfo = JSON.parse(info.data['ykInfo']);
        console.log(dataList);
        console.log(ykInfo);
        deviceList.value = ykInfo;
      }
      useCommonStoreWithOut().setVariableData(dataList);
      dataList.map((item) => {
        if (item['dot'] == 0) {
          item['id'] = `a${item['dot']}`;
        } else {
          item['id'] = item['dot'];
        }
        // 提升机泵液位
        if (item['vtype'] === 'FLOAT') {
          let data = parseFloat(item['value']).toFixed(2);
          item['text'] = Number(data);
          // item['text'] = Number(item['value']);
        } else {
          item['text'] = item['value'];
        }
        if (item['id'] == 6) {
          item['progress'] = item['value'] / 10;
        }
        meta2d.setValue({
          ...item,
        });
      });
    }
  };
}

/**
 * 获取站点信息
 */
function initStationInfo() {
  let id = proxy.$route.query.id;
  initWebSocket();
  stationInfoApi({ id }).then((res) => {
    if (res && res['graph']) {
      let data = JSON.parse(res['graph']);
      data['locked'] = 1;
      data['rule'] = false;
      meta2d.open(data);
      meta2d.fitView();
    }
    stationInfo.value = res;
    let { stationCode } = res;
    initEquipmentList(stationCode);
  });
}

/**
 * 获取设备列表
 */
function initEquipmentList(stationCode) {
  equipmentListApi({ stationCode }).then((res) => {
    // deviceList.value = res.map((_) => {
    //   _['control'] = 0;
    //   return _;
    // });
  });
}

/**
 * 发送设备信息
 */
function saveDeviceMessage(vo) {
  let { messageId, messageTime, messageType } = socketMessage.value;
  let data = {
    messageId,
    messageTime,
    messageType: 3,
    data: {
      'macro-id': vo['macro-id'],
      value: vo['state']['running'],
    },
  };
  meta2d.websocket.send(JSON.stringify(data));
}

function saveDeviceAuto(vo) {
  setTimeout(() => {
    let { messageId, messageTime, messageType } = socketMessage.value;
    let auto = vo['state']['auto'];
    let data = {
      messageId,
      messageTime,
      messageType: 3,
      data: {
        'macro-id': vo['macro-id'],
        value: auto == 0 ? 2 : 3,
      },
    };
    meta2d.websocket.send(JSON.stringify(data));
  }, 800);
}

onMounted(() => {
  initStationInfo();
});
</script>

<style lang="less" scoped>
.station-device-view {
  margin: 12px;
  background: #fff;
  .tip {
    width: 100%;
    height: 44px;
    padding: 0 0 0 43.3px;
    background: url('@/assets/images/img-17.png') no-repeat;
    background-size: 100% 100%;
    line-height: 44px;
    :deep(.ant-page-header) {
      padding: 0;
      .ant-page-header-heading {
        .ant-page-header-heading-left {
          margin: 0;
        }
        .ant-page-header-back .anticon-arrow-left,
        .ant-page-header-heading-title {
          color: #fff;
        }
      }
    }
    span {
      font-size: 16px;
      color: #fff;
    }
  }
  .device-main {
    margin: 24px;
    height: calc(100vh - 224px);
    .device {
      width: 50%;
      height: calc(100% - 24px);
      margin-right: 6px;
      overflow: hidden;
      overflow-y: scroll;
      .ant-card {
        width: 33.3%;
        height: 250px;
      }
      &.device-grid {
        display: grid;
        grid-template-columns: repeat(3, 1fr);
        grid-gap: 12px 12px;
        .ant-card {
          width: 100%;
          height: 250px;
        }
      }
    }
    .meta-main {
      width: 50%;
      height: 100%;
      #device-meta {
        height: calc(100vh - 225px);
      }
    }
  }
}
</style>